import {
  generateElevation,
  generateSectorShape,
  drawACircle,
  drawLine,
  generateDistanceIdentification,
  type Sector
} from "./SafeShootingRealmUtil";
import type GeoJSON from "geojson";

// 存储每组数据对应的所有 id
const groupIdsMap: Record<string, string[]> = {};

// 初始化射界
export function initShootingRealm(
  map: any,
  id: string,
  data: { distance: number; angle: number }[],
  center: [number, number],
  sector: Sector[] = []
) {
  if (data.length === 0) {
    console.log("请提供厂家可匹配的数据!");
    return;
  }
  const circleFeature = drawACircle(data, center);
  const lineFeature = drawLine(data[0].distance, center);
  const elevationFeature = generateElevation(data, center);
  const kilometreFeature = generateDistanceIdentification(center);
  const features = [...circleFeature, ...lineFeature, ...elevationFeature, ...kilometreFeature];

  if (sector.length > 0) {
    sector.forEach(item => {
      const sectorFeature = generateSectorShape(center, item.radius1, item.radius2, item.angleStart, item.angleEnd);
      features.push(sectorFeature);
    });
  }

  const geojson: GeoJSON.FeatureCollection<GeoJSON.Geometry> = {
    type: "FeatureCollection",
    features
  };
  loadToMap(map, id, geojson);
}
// 添加图层到 Mapbox 地图
export function loadToMap(map: any, id: string, geojson: GeoJSON.FeatureCollection<GeoJSON.Geometry>) {
  const sourceId = `${id}-geojson-source`;
  const currentGroupIds: string[] = [];
  currentGroupIds.push(sourceId);

  map.addSource(sourceId, {
    type: "geojson",
    data: geojson
  });
  console.log(geojson);

  // 添加线图层
  const lineLayerId = `${id}-line-layer`;
  currentGroupIds.push(lineLayerId);
  map.addLayer({
    id: lineLayerId,
    type: "line",
    source: sourceId,
    filter: ["==", ["geometry-type"], "LineString"],
    paint: {
      "line-color": "blue",
      "line-width": 2
    }
  });

  // 添加点图层
  const pointLayerId = `${id}-point-layer`;
  currentGroupIds.push(pointLayerId);
  map.addLayer({
    id: pointLayerId,
    type: "circle",
    source: sourceId,
    filter: ["==", ["geometry-type"], "Point"],
    paint: {
      "circle-color": ["get", "color"],
      "circle-radius": ["get", "radius"]
    }
  });

  // 添加文字标签图层
  const textLabelLayerId = `${id}-text-label-layer`;
  currentGroupIds.push(textLabelLayerId);
  map.addLayer({
    id: textLabelLayerId,
    type: "symbol",
    source: sourceId,
    filter: ["==", ["geometry-type"], "Point"],
    layout: {
      "text-field": ["to-string", ["get", "text"]],
      "text-offset": [0, 1.2],
      "text-anchor": "top",
      "text-font": ["MicrosoftYaHei"]
    },
    paint: {
      "text-color": "black",
      "text-halo-color": "white",
      "text-halo-width": 1
    }
  });

  // 添加面图层
  const polygonLayerId = `${id}-polygon-layer`;
  currentGroupIds.push(polygonLayerId);
  map.addLayer({
    id: polygonLayerId,
    type: "fill",
    source: sourceId,
    filter: ["==", ["geometry-type"], "Polygon"],
    paint: {
      "fill-color": "green",
      "fill-opacity": 0.5
    }
  });

  // 将当前组的所有 id 存储到 groupIdsMap 中
  groupIdsMap[id] = currentGroupIds;
}
// 删除单组点线面
export function removeGroupFromMap(map: any, id: string) {
  const groupIds = groupIdsMap[id];
  if (groupIds) {
    // 先删除所有图层
    const layerIds = groupIds.filter(groupId => groupId.endsWith("-layer"));
    layerIds.forEach(layerId => {
      if (map.getLayer(layerId)) {
        map.removeLayer(layerId);
      }
    });

    // 再删除数据源
    const sourceId = groupIds.find(groupId => groupId.endsWith("-source"));
    if (sourceId && map.getSource(sourceId)) {
      map.removeSource(sourceId);
    }

    // 从 groupIdsMap 中删除该组的记录
    delete groupIdsMap[id];
  }
}
